'use client';

import { useState, useEffect } from 'react';
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { eventBus } from '@/modules/application/utils/eventBus';

export default function EventBusDemoPage() {
  const [userName, setUserName] = useState('');
  const [userEmail, setUserEmail] = useState('');
  const [theme, setTheme] = useState<'light' | 'dark'>('light');
  const [notificationText, setNotificationText] = useState('');
  const [notifications, setNotifications] = useState<Array<{ message: string; timestamp: number }>>([]);
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  // Subscribe to events
  useEffect(() => {
    const unsubscribeLogin = eventBus.on('app:userLogin', (userData) => {
      if (userData) {
        console.log('User logged in:', userData);
        setIsLoggedIn(true);
      }
    });

    const unsubscribeLogout = eventBus.on('app:userLogout', () => {
      console.log('User logged out');
      setIsLoggedIn(false);
    });

    const unsubscribeTheme = eventBus.on('app:themeChange', (themeData) => {
      if (themeData) {
        console.log('Theme changed to:', themeData.theme);
        setTheme(themeData.theme);
      }
    });

    const unsubscribeNotification = eventBus.on('app:notificationAdd', (notification) => {
      if (notification) {
        console.log('New notification:', notification.message);
        setNotifications(prev => [...prev, notification]);
      }
    });
    
    // Clean up subscriptions
    return () => {
      unsubscribeLogin();
      unsubscribeLogout();
      unsubscribeTheme();
      unsubscribeNotification();
    };
  }, []);

  const handleLogin = () => {
    if (userName && userEmail) {
      eventBus.trigger('app:userLogin', {
        id: Date.now(),
        name: userName,
        email: userEmail
      });
    }
  };

  const handleLogout = () => {
    eventBus.trigger('app:userLogout');
  };

  const handleThemeChange = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    eventBus.trigger('app:themeChange', {
      theme: newTheme
    });
  };

  const handleAddNotification = () => {
    if (notificationText.trim()) {
      eventBus.trigger('app:notificationAdd', {
        message: notificationText,
        timestamp: Date.now()
      });
      setNotificationText('');
    }
  };

  return (
    <div className={`min-h-screen ${theme === 'dark' ? 'bg-gray-900 text-white' : 'bg-gray-50 text-gray-900'} p-4`}>
      <div className="max-w-4xl mx-auto space-y-8">
        <h1 className="text-3xl font-bold">EventBus Demo</h1>
        
        <Card className={theme === 'dark' ? 'bg-gray-800' : 'bg-white'}>
          <CardHeader>
            <CardTitle>Authentication</CardTitle>
            <CardDescription>Simulate user login/logout events</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {!isLoggedIn ? (
              <>
                <div className="space-y-2">
                  <Label htmlFor="username">Username</Label>
                  <Input
                    id="username"
                    type="text"
                    value={userName}
                    onChange={(e) => setUserName(e.target.value)}
                    placeholder="Enter your username"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    value={userEmail}
                    onChange={(e) => setUserEmail(e.target.value)}
                    placeholder="Enter your email"
                  />
                </div>
                <Button onClick={handleLogin} disabled={!userName || !userEmail}>Login</Button>
              </>
            ) : (
              <div className="space-y-4">
                <p>Welcome, {userName}!</p>
                <Button onClick={handleLogout}>Logout</Button>
              </div>
            )}
          </CardContent>
        </Card>

        <Card className={theme === 'dark' ? 'bg-gray-800' : 'bg-white'}>
          <CardHeader>
            <CardTitle>Theme Settings</CardTitle>
            <CardDescription>Toggle between light and dark themes using EventBus</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center space-x-4">
              <span>Current theme: <strong>{theme}</strong></span>
              <Button onClick={handleThemeChange}>
                Switch to {theme === 'light' ? 'Dark' : 'Light'} Theme
              </Button>
            </div>
          </CardContent>
        </Card>

        <Card className={theme === 'dark' ? 'bg-gray-800' : 'bg-white'}>
          <CardHeader>
            <CardTitle>Notifications</CardTitle>
            <CardDescription>Add and view notifications using EventBus</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="notification">Add Notification</Label>
              <div className="flex space-x-2">
                <Input
                  id="notification"
                  type="text"
                  value={notificationText}
                  onChange={(e) => setNotificationText(e.target.value)}
                  placeholder="Enter notification text"
                />
                <Button onClick={handleAddNotification}>Add</Button>
              </div>
            </div>
            
            <div className="space-y-2">
              <h3 className="font-medium">Notification History:</h3>
              {notifications.length > 0 ? (
                <ul className="space-y-2">
                  {notifications.map((notification, index) => (
                    <li key={index} className={`p-2 rounded-md ${theme === 'dark' ? 'bg-gray-700' : 'bg-gray-100'}`}>
                      <p>{notification.message}</p>
                      <p className="text-sm opacity-75">
                        {new Date(notification.timestamp).toLocaleTimeString()}
                      </p>
                    </li>
                  ))}
                </ul>
              ) : (
                <p className="text-gray-500 italic">No notifications yet</p>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}